package com.supermap.panes;

import com.supermap.Helper;
import com.supermap.analyst.networkanalyst.*;
import com.supermap.data.*;
import com.supermap.mapping.Map;
import com.supermap.mapping.TrackingLayer;
import com.supermap.panes.advance.SettingPane;
import com.supermap.ui.Action;
import com.supermap.ui.MapControl;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;

public class ServiceAreaAnalystSettingPane extends SettingPane implements MouseListener {
    private MapControl mapControl;
    private JSplitPane dataPane;
    private JButton dynamicBtn;

    private DatasetVector datasetVector;
    private TransportationAnalyst transportationAnalyst;
    private Point2Ds points;
    private Point2Ds barrierPoints;
    private int addPoints;
    private int routePartIndex;
    private int routePartPointIndex;
    private PointMs routePart;

    public ServiceAreaAnalystSettingPane(String title, MapControl mapControl, DatasetVector datasetVector, JSplitPane dataPane) {
        super(title, new Object[]{mapControl, datasetVector, dataPane});
    }

    @Override
    public void mouseClicked(MouseEvent e) {

    }

    @Override
    public void mousePressed(MouseEvent e) {
        if (e.getButton() == 1) {
            Point point = new Point(e.getX(), e.getY());
            Map map = mapControl.getMap();
            Point2D mapPoint = map.pixelToMap(point);
            if (map.getBounds().contains(mapPoint)) {
                switch (addPoints) {
                    case 1:
                        addPoint(mapPoint);
                        break;
                    default:
                        break;
                }
            }
        }
    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

    @Override
    protected void initializeArgs(Object[] args) {
        this.mapControl = (MapControl) args[0];
        this.datasetVector = (DatasetVector) args[1];
        this.dataPane = (JSplitPane) args[2];
        points = new Point2Ds();
        barrierPoints = new Point2Ds();
        addPoints = 0;
        routePartIndex = 0;
        routePartPointIndex = 0;
    }

    @Override
    protected void initializeCore() {
        super.confirmBtn.setText("分析");

        transportationAnalyst = new TransportationAnalyst();
        TransportationAnalystSetting transportationAnalystSetting = new TransportationAnalystSetting();
        transportationAnalystSetting.setNetworkDataset(datasetVector);
        WeightFieldInfos weightFieldInfos = new WeightFieldInfos();
        WeightFieldInfo weightFieldInfo = new WeightFieldInfo();
        weightFieldInfo.setFTWeightField("smLength");
        weightFieldInfo.setTFWeightField("smLength");
        transportationAnalystSetting.setEdgeIDField("SmID");
        transportationAnalystSetting.setNodeIDField("SmNodeID");
        transportationAnalystSetting.setFNodeIDField("SmFNode");
        transportationAnalystSetting.setTNodeIDField("SmTNode");
        FieldInfos fieldInfos = datasetVector.getFieldInfos();
        if (Environment.getCurrentCulture().contentEquals("zh-CN")) {
            if (fieldInfos.indexOf("roadName") != -1) {
                transportationAnalystSetting.setEdgeNameField("roadName");
            } else {
                transportationAnalystSetting.setEdgeNameField("name");
            }
        } else {
            if (fieldInfos.indexOf("roadName_en") != -1) {
                transportationAnalystSetting.setEdgeNameField("roadName_en");
            } else {
                transportationAnalystSetting.setEdgeNameField("name_en");
            }
        }
        weightFieldInfo.setName("length");
        weightFieldInfos.add(weightFieldInfo);
        transportationAnalystSetting.setWeightFieldInfos(weightFieldInfos);
        transportationAnalyst.setAnalystSetting(transportationAnalystSetting);
        transportationAnalyst.load();

        mapControl.removeMouseListener(this);
        mapControl.addMouseListener(this);

        JToolBar toolBar = new JToolBar();
        super.mainPanel.add(toolBar, BorderLayout.NORTH);

        JButton addPointBtn = new JButton("添加服务站点");
        addPointBtn.addActionListener(e -> {
            mapControl.setAction(Action.NULL);
            addPoints = 1;
        });
        toolBar.add(addPointBtn);

        // TODO: 初始化参数面板
        JButton clearBtn = new JButton("清空");
        clearBtn.addActionListener(e -> doClose());
        toolBar.add(clearBtn);
    }

    @Override
    protected void doConfirm() {
        mapControl.setAction(Action.SELECT2);
        TransportationAnalystParameter parameter = new TransportationAnalystParameter();
        parameter.setPoints(points);
        parameter.setBarrierPoints(barrierPoints);
        parameter.setWeightName("length");
        parameter.setNodesReturn(true);
        parameter.setEdgesReturn(true);
        parameter.setPathGuidesReturn(true);
        parameter.setRoutesReturn(true);
        parameter.setServiceBufferRadius(1);
        double[] weights = new double[points.getCount()];
        for (int i = 0; i < weights.length; i++) {
            weights[i] = (i + 1) * 100;
        }
        TransportationAnalystResult pathResult = transportationAnalyst.findServiceArea(parameter, weights, true, false);

        addPoints = 0;

        Map map = mapControl.getMap();
        TrackingLayer trackingLayer = map.getTrackingLayer();
        int routeIndex = trackingLayer.indexOf("Route");
        if (routeIndex != -1) {
            trackingLayer.remove(routeIndex);
        }

        ServiceAreaResult serviceAreaResult = (ServiceAreaResult) pathResult;
        GeoRegion[] serviceRegions = serviceAreaResult.getServiceRegions();
        if (serviceRegions != null && serviceRegions.length > 0) {
            for (GeoRegion geoRegion : serviceRegions) {
                GeoStyle geoStyle = new GeoStyle();
                Color randomColor = Helper.randomColor();
                geoStyle.setFillBackColor(randomColor);
                geoStyle.setFillForeColor(randomColor);
                geoStyle.setFillOpaqueRate(50);
                geoStyle.setLineColor(randomColor);
                geoRegion.setStyle(geoStyle);
                trackingLayer.add(geoRegion, "ServiceArea");
            }
            map.refreshTrackingLayer();
        }
    }

    @Override
    protected void doClose() {
        points.clear();
        barrierPoints.clear();
        routePartIndex = 0;
        routePartPointIndex = 0;
        Map map = mapControl.getMap();
        map.getTrackingLayer().clear();
        map.refreshTrackingLayer();
        dataPane.setBottomComponent(null);
        dynamicBtn.setEnabled(false);
    }

    private void addPoint(Point2D mapPoint) {
        points.add(mapPoint);
        GeoPoint geoPoint = new GeoPoint(mapPoint);
        GeoStyle geoStyle = new GeoStyle();
        geoStyle.setMarkerSize(new Size2D(6, 6));
        geoStyle.setFillBackColor(Color.GREEN);
        geoStyle.setFillForeColor(Color.GREEN);
        geoStyle.setLineColor(Color.GREEN);
        geoPoint.setStyle(geoStyle);

        Map map = mapControl.getMap();
        TrackingLayer trackingLayer = map.getTrackingLayer();
        trackingLayer.add(geoPoint, "Points");

        TextPart textPart = new TextPart();
        textPart.setX(geoPoint.getX());
        textPart.setY(geoPoint.getY());
        textPart.setText("服务站点" + points.getCount());
        GeoText geoText = new GeoText(textPart);
        TextStyle textStyle = new TextStyle();
        textStyle.setForeColor(Color.GREEN);
        geoText.setTextStyle(textStyle);
        trackingLayer.add(geoText, "Points");

        map.refreshTrackingLayer();
    }
}
